package httpcommon

import (
	"net/http"
	"time"

	lg "gitee.com/bm_guangge/bm_common/log"
)

func InitHttpServer(HttpListenPort, HttpsListenPort, CertFile, KeyFile string, backend bool) {
	// InitHandler()
	server := http.Server{
		Addr:        HttpListenPort,
		Handler:     &MyHandler{},
		ReadTimeout: 5 * time.Second,
	}

	servers := http.Server{
		Addr:        HttpsListenPort,
		Handler:     &MyHandler{},
		ReadTimeout: 5 * time.Second,
	}

	go func() {
		if len(CertFile) <= 0 {
			lg.ELogger.Println("cert is empty...")
		} else {
			lg.ILogger.Println("ListenAndServeTLS listen ", HttpsListenPort, "...")
			err := servers.ListenAndServeTLS(CertFile, KeyFile)
			if err != nil {
				lg.ELogger.Println("ListenAndServeTLS:", err.Error())
			}
		}
	}()

	if backend {
		go func() {
			lg.ILogger.Println("ListenAndServe listen ", HttpListenPort, "...")

			err := server.ListenAndServe()
			if err != nil {
				lg.ELogger.Println("ListenAndServe:", err.Error())
			}
		}()
	} else {
		lg.ILogger.Println("ListenAndServe listen ", HttpListenPort, "...")

		err := server.ListenAndServe()
		if err != nil {
			lg.ELogger.Println("ListenAndServe:", err.Error())
		}
	}
}

// 带本地文件服务的接口
func InitHttpServerFile(HttpListenPort, HttpsListenPort, HttpFilePort, FileRoot, CertFile, KeyFile string, backend bool) {
	// InitHandler()
	server := http.Server{
		Addr:        HttpListenPort,
		Handler:     &MyHandler{},
		ReadTimeout: 5 * time.Second,
	}

	servers := http.Server{
		Addr:        HttpsListenPort,
		Handler:     &MyHandler{},
		ReadTimeout: 5 * time.Second,
	}

	serverf := http.Server{
		Addr:    HttpFilePort,
		Handler: http.FileServer(http.Dir(FileRoot)),
	}

	go func() {
		if len(CertFile) <= 0 {
			lg.ELogger.Println("cert is empty...")
		} else {
			lg.ILogger.Println("ListenAndServeTLS listen ", HttpsListenPort, "...")
			err := servers.ListenAndServeTLS(CertFile, KeyFile)
			if err != nil {
				lg.ELogger.Println("ListenAndServeTLS:", err.Error())
			}
		}
	}()

	go func() {
		err := serverf.ListenAndServe()
		if err != nil {
			lg.ELogger.Println("FileServer:", err.Error())
		}
	}()

	if backend {
		go func() {
			lg.ILogger.Println("ListenAndServe listen ", HttpListenPort, "...")

			err := server.ListenAndServe()
			if err != nil {
				lg.ELogger.Println("ListenAndServe:", err.Error())
			}
		}()
	} else {
		lg.ILogger.Println("ListenAndServe listen ", HttpListenPort, "...")

		err := server.ListenAndServe()
		if err != nil {
			lg.ELogger.Println("ListenAndServe:", err.Error())
		}
	}
}
